<?php

class VideoController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array( 
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete','index','view','vcreate','acreate','update','viewfile'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionVcreate()
	{
		$model=new Video;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Video']))
		{
			$model->attributes=$_POST['Video'];
            //保存上传图片 
            $uploadedimage = CUploadedFile::getInstance($model, 'cover');
            $datetime=Yii::app()->format->formatDate(time());
            $uploaddir = dirname(Yii::app()->basePath) . '/uploads/'.$datetime.'/';
            if (!file_exists($uploaddir)) {
                mkdir($uploaddir, 0755, true); //第三个参数为true即可以创建多极目录
            }
            if (is_object($uploadedimage) && get_class($uploadedimage) === 'CUploadedFile') {
                $filename = md5(uniqid());
                $ext = $uploadedimage->extensionName;
                $uploadfile = $uploaddir . $filename . '.' . $ext;
                $uploadedimage->saveAs($uploadfile);
                $model->cover = '/uploads/' .$datetime.'/'. $filename . '.' . $ext;
            }
			if($model->save())
				$this->redirect(array('admin'));
		}
         $category = Category::model()->findAll("categorytype =:categorytype",array(":categorytype"=>'电影'));
		$this->render('create',array(
			'model'=>$model,'category'=>$category,
		));
	}

    public function actionAcreate()
    {
        $model=new Video;

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if(isset($_POST['Video']))
        {
            $model->attributes=$_POST['Video'];
            //保存上传图片 
            $uploadedimage = CUploadedFile::getInstance($model, 'cover');
            $datetime=Yii::app()->format->formatDate(time());
            $uploaddir = dirname(Yii::app()->basePath) . '/uploads/'.$datetime.'/';
            if (!file_exists($uploaddir)) {
                mkdir($uploaddir, 0755, true); //第三个参数为true即可以创建多极目录
            }
            if (is_object($uploadedimage) && get_class($uploadedimage) === 'CUploadedFile') {
                $filename = md5(uniqid());
                $ext = $uploadedimage->extensionName;
                $uploadfile = $uploaddir . $filename . '.' . $ext;
                $uploadedimage->saveAs($uploadfile);
                $model->cover = '/uploads/' .$datetime.'/'. $filename . '.' . $ext;
            }
            if($model->save())
                $this->redirect(array('admin'));
        }
        $category = Category::model()->findAll("categorytype =:categorytype",array(":categorytype"=>'应用'));
        $this->render('create',array(
            'model'=>$model,'category'=>$category,
        ));
    }

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Video']))
		{
            $oldpictureUrl = dirname(Yii::app()->basePath).$model->cover;
			$model->attributes=$_POST['Video'];
            $uploadedimage = CUploadedFile::getInstance($model, 'cover'); 
            $datetime=Yii::app()->format->formatDate(time());
            $uploaddir = dirname(Yii::app()->basePath) . '/uploads/'.$datetime.'/';
            if (!file_exists($uploaddir)) {
                mkdir($uploaddir, 0755, true); //第三个参数为true即可以创建多极目录
            }
            if (is_object($uploadedimage) && get_class($uploadedimage) === 'CUploadedFile') {
                $filename = md5(uniqid());
                $ext = $uploadedimage->extensionName;
                $uploadfile = $uploaddir . $filename . '.' . $ext;
                $uploadedimage->saveAs($uploadfile);
                $model->cover = '/uploads/' .$datetime.'/'. $filename . '.' . $ext;
                //判断是否旧的logo，如果存在并删除就文件
                if(file_exists($oldpictureUrl)){
                    unlink($oldpictureUrl);
                }
            }
			if($model->save())
				$this->redirect(array('admin'));
		}

        //先得到修改的类型
        $category = Category::model()->findAll("categorytype =:categorytype",array(":categorytype"=>$model->category.categorytype));

		$this->render('update',array(
			'model'=>$model,'category'=>$category,
		));
	}
 

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		// $dataProvider=new CActiveDataProvider('Video');
		// $this->render('index',array(
		// 	'dataProvider'=>$dataProvider,
		// )); 
        $this->redirect(array('admin')); 
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Video('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Video']))
			$model->attributes=$_GET['Video'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}  
    /**
     * undocumented function
     *
     * @return void
     * @author 
     **/
    public function actionViewfile()
    {
        $basepath= dirname(Yii::app()->BasePath);
        $path = $basepath.'/uploads/videos';
       
        $model=$this->traverse($path,$basepath); 
        $returnhtml ='<div id="videoview-grid" class="grid-view">
                    <table class="itemsinfo">
                    <thead><tr>
                    <th id="video-grid_c0">序号</th><th id="video-grid_c1">类型</th><th id="video-grid_c2">文件名</th><th id="video-grid_c3">文件大小</th><th class="button-column" id="video-grid_c4">操作</th></tr>
                    </thead>
                    <tbody>';
            foreach ($model as $key => $value) {
                $viewhtml='';
                if(($key % 2) ==0){
                    $viewhtml.='<tr class="odd">';
                }else{
                    $viewhtml.='<tr class="even">';
                }
                $viewhtml.=' <td width="40px" style="text-align:center">'.($key+1).'</td>';
                $viewhtml.=' <td>'.$value['filetype'].'</td>';
                $viewhtml.=' <td>'.$value['name'].'</td>';
                $viewhtml.=' <td width="80px" style="text-align:center">'.$value['size'].'</td>';//"'.$value['filepath'].'","'.$value['size'].'"
                $viewhtml.=' <td class="button-column"><a class="delete" title="删除" href="javascript:callbacks(\''.$value['filepath'].'\',\''.$value['size'].'\');$.colorbox.close();"><img src="'.Yii::app()->request->baseUrl.'/images/admin/xuanz.png" alt="关联文件"></a></td>';
                $viewhtml.=' </tr>'; 
                $returnhtml.=$viewhtml;
            }
               
             $returnhtml .='</tbody></table> </div>';
             echo $returnhtml ;
    }

    /**
     * 得到文件夹下面所有文件 
     **/
    private function traverse($path,$basepath)
    { 
      $files=array();
      $current_dir = opendir($path);    //opendir()返回一个目录句柄,失败返回false 
      while(($file = readdir($current_dir)) !== false) {    //readdir()返回打开目录句柄中的一个条目
           $sub_dir = $path . DIRECTORY_SEPARATOR . $file;    //构建子目录路径 
             if($file == '.' || $file == '..'|| $file == '.DS_Store'|| $file == 'README.txt' || $file == '._README.txt') {
                   continue;
              } else if(is_dir($sub_dir)) {    //如果是目录,进行递归
                  //echo 'Directory ' . $file . ':<br>';
                  $files=array_merge($files,$this->traverse($sub_dir,$basepath));
                  // $this->traverse($sub_dir,$files);
              } else {    //如果是文件,直接输出
                 $filearray['name']= $file;
                 $filearray['size']= round(filesize($path.'/'.$file)/(1024*1024),2);
                 $path_parts = pathinfo($path.'/'.$file);
                 $filearray['filetype']= $path_parts['extension']; 
                 $filearray['filepath']=str_replace($basepath,'',$path).'/'.$file;
                 //echo '====' . $path . ': ' . $file . ': '.round(filesize($path.'/'.$file)/(1024*1024),2).'MB<br>';
                 $files[] = $filearray;
              } 
        } 
        return $files;
 
    }
       
	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Video the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=Video::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param Video $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='video-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
